package model

import (
	"strings"
	"time"
	"gitee.com/zxs-micro/zxs-micro-common/utils"
)

var tokentimeformatter = "2006-01-02 15:04:05"

type TokenModel struct {
	Account    string    `json:"account"`
	Role       string    `json:"role"`
	CreateTime time.Time `json:"create_time"`
	LastTime   time.Time `json:"last_time"`
	Creator    string    `json:"creator"`
}

func (t *TokenModel) ToString() string {
	sb := new(strings.Builder)
	sb.WriteString("{\"account\":\"")
	sb.WriteString(t.Account)
	sb.WriteString("\",\"role\":\"")
	sb.WriteString(t.Role)
	sb.WriteString("\",\"creator\":\"")
	sb.WriteString(t.Creator)
	sb.WriteString("\",\"create_time\":\"")
	sb.WriteString(t.CreateTime.Format(tokentimeformatter))
	sb.WriteString("\",\"last_time\":\"")
	sb.WriteString(t.LastTime.Format(tokentimeformatter))
	sb.WriteString("\"}")
	return sb.String()
}

func (t *TokenModel) ParseObj(s string) error {
	m1 := utils.Jsonstr2Map(s)
	t.Account = m1["account"]
	t.Role = m1["role"]
	t.Creator = m1["creator"]
	ct, err := time.Parse(tokentimeformatter, m1["create_time"])
	if err != nil {
		return err
	}
	lt, err := time.Parse(tokentimeformatter, m1["last_time"])
	t.Account = m1["account"]
	t.Role = m1["role"]
	t.Creator = m1["creator"]
	t.CreateTime = ct
	t.LastTime = lt
	return nil
}

//{"account":"a1","role":"r1","creator":"c1","create_time":"...","last_time":"..."}
func (t TokenModel) MarshalJSON() ([]byte, error) {
	sb := new(strings.Builder)
	sb.WriteString("{\"account\":\"")
	sb.WriteString(t.Account)
	sb.WriteString("\",\"role\":\"")
	sb.WriteString(t.Role)
	sb.WriteString("\",\"creator\":\"")
	sb.WriteString(t.Creator)
	sb.WriteString("\",\"create_time\":\"")
	sb.WriteString(t.CreateTime.Format(tokentimeformatter))
	sb.WriteString("\",\"last_time\":\"")
	sb.WriteString(t.LastTime.Format(tokentimeformatter))
	sb.WriteString("\"}")
	return []byte(sb.String()), nil
}

func (t *TokenModel) UnmarshalJSON(data []byte) error {
	str := string(data)
	var err error
	m1 := utils.Jsonstr2Map(str)
	t.Account = m1["account"]
	t.Role = m1["role"]
	t.Creator = m1["creator"]
	ct, err := time.Parse(tokentimeformatter, m1["create_time"])
	if err != nil {
		return err
	}
	lt, err := time.Parse(tokentimeformatter, m1["last_time"])
	*t = TokenModel{
		Account:    m1["account"],
		Role:       m1["role"],
		Creator:    m1["creator"],
		CreateTime: ct,
		LastTime:   lt,
	}
	return err
}
